﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class AddressesCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        //    protected static List<Addresses> _list;
        /// <summary>
        /// Список адресов
        /// </summary>
        public List<Addresses> AddressesList
        {
            get
            {
                //if (_list == null)
                //    _list = DB.Entities.Addresses.ToList();
                //return _list;
                return Entities.Addresses.ToList();
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            throw new NotImplementedException();
        }


        /// <summary>
        /// Получение объекта по идентификатору
        /// </summary>
        /// <param name="id">Идентификатор</param>
        /// <returns>Объект</returns>
        public override object GetItemById(int id)
        {
            return Entities.Addresses.Find(id);
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return null;
        }


        /// <summary>
        /// Получение списка адресов по идентификатору юридического лица
        /// </summary>
        /// <param name="legalEntityId">Индентификатор юридического лица</param>
        /// <returns>Список адресов</returns>
        public List<Addresses> GetAddressesByLegalEntityId(int legalEntityId)
        {
            return AddressesList.Where(c => c.IdLegalEntity == legalEntityId).ToList();
        }


        /// <summary>
        /// Добавление элемента в коллекцию
        /// </summary>
        /// <param name="item">Элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        public new bool Add(object item, string userLogin)
        {
            var address = item as Addresses;

            SetPrimary(address);

            return base.Add(address, userLogin);
        }

        ///// <summary>
        ///// Удаление элемента в коллекцию
        ///// </summary>
        ///// <param name="item">Элемент</param>
        //public new bool Delete(object item)
        //{
        //    var address = item as Addresses;

        //    SetPrimary(address);

        //    return base.Delete(address);
        //}

        /// <summary>
        /// Установка основного адреса
        /// </summary>
        /// <param name="address">Адрес</param>
        protected void SetPrimary(Addresses address)
        {
            if (address.IsPrimary == null)
                address.IsPrimary = false;

            bool hasPrimaryAddress = false;

            //if (address.Customer != null)
            //    foreach (Addresses addr in address.LegalEntities.Addresses)
            //    {
            //        if (addr.IsPrimary != null && (bool) addr.IsPrimary)
            //        {
            //            hasPrimaryAddress = true;
            //            break;
            //        }
            //    }

            if (address.Customer != null && address.IdLegalEntity > 0)
            {
                var leCol = new LegalEntitiesCollection();
                var le = (LegalEntities) leCol.GetItemById((int)address.IdLegalEntity);
                if(le!=null)
                {
                    foreach (var addr in le.Addresses)
                    {
                        if (addr.IsPrimary == null || !((bool) addr.IsPrimary)) continue;
                        hasPrimaryAddress = true;
                        break;
                    }
                }
            }


            if (!hasPrimaryAddress)
                address.IsPrimary = true;
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (Addresses);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(AddressesList);
        }


        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin, bool save = true)
        {
            var newObject = (Addresses) item;
            if (newObject == null)
                return false;


            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as Addresses;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Comments))
                object4Update.Comments = newObject.Comments;

            if (!string.IsNullOrEmpty(newObject.Fax))
                object4Update.Fax = newObject.Fax;

            if (!string.IsNullOrEmpty(newObject.House))
                object4Update.House = newObject.House;

            if (!string.IsNullOrEmpty(newObject.Phone))
                object4Update.Phone = newObject.Phone;

            if (!string.IsNullOrEmpty(newObject.Street))
                object4Update.Street = newObject.Street;

            if (!string.IsNullOrEmpty(newObject.ZipCode))
                object4Update.ZipCode = newObject.ZipCode;

            if (!string.IsNullOrEmpty(newObject.House))
                object4Update.House = newObject.House;


            if (newObject.IdAddressesItem != null)
            {
                object4Update.IdAddressesItem = newObject.IdAddressesItem;
            }

            if (newObject.IdAddressesType != null)
            {
                object4Update.IdAddressesType = newObject.IdAddressesType;
            }

            if (newObject.IdLegalEntity != null)
            {
                object4Update.IdLegalEntity = newObject.IdLegalEntity;
            }

            if (newObject.IsPrimary != null)
            {

                object4Update.IsPrimary = newObject.IsPrimary;
               if((bool) object4Update.IsPrimary)
               {
                   

                   foreach (var addr in object4Update.LegalEntities.Addresses)
                   {
                       addr.IsPrimary = false;
                   }
                   object4Update.IsPrimary = true;
               }
            }

            SetPrimary(object4Update);

            object4Update.IsActive = newObject.IsActive;


            return base.Update(object4Update, userLogin, save);
        }

        #endregion
    }
}